package com.bobi.tfca.ui.mainnavigation.message.letter

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.navigation.findNavController
import com.bobi.tfca.R
import com.bobi.tfca.base.BaseFragment
import com.bobi.tfca.constants.MessageStatusEnum
import com.bobi.tfca.databinding.FragmentLetterDetailBinding
import com.bobi.tfca.util.LogUtil

class LetterDetailFragment : BaseFragment<FragmentLetterDetailBinding, LetterDetailFragmentVM>(
    FragmentLetterDetailBinding::inflate,
    LetterDetailFragmentVM::class.java,
    true
) {

    @SuppressLint("ResourceType", "UseRequireInsteadOfGet")
    override fun initFragment(
        binding: FragmentLetterDetailBinding,
        viewModel: LetterDetailFragmentVM?,
        savedInstanceState: Bundle?
    ) {
        // 写信人姓名
        val senderName = publicViewModel!!.message.value?.senderName ?: ""

        // 设置头部菜单的按钮
        setTopPanelStyle(binding, senderName)

        // 设置监听
        viewModel!!.letter.observe(viewLifecycleOwner) {
            binding.letter = it
        }

        // 如果这个信件是未读的，那么就将未读信件减一
        if (publicViewModel!!.message.value!!.messageStatus == MessageStatusEnum.RECEIVED.code) {
            publicViewModel!!.newLetterNum.value = publicViewModel!!.newLetterNum.value?.minus(1)
        }
    }

    /**
     * 设置顶部面板的样式
     */
    private fun setTopPanelStyle(binding: FragmentLetterDetailBinding, senderName: String) {
        val topPanel = binding.topPanel
        val leftImage = topPanel.leftImage
        leftImage.setOnClickListener {
            // 重置letter
            publicViewModel!!.resetMessage()
            requireActivity().findNavController(R.id.app_nav).navigateUp()
        }
        val rightLayout = topPanel.rightLayout
        rightLayout.visibility = View.GONE
        val title = topPanel.titleText
        // 发送方
        title.text = senderName
    }


    override fun resumeFragment(viewModel: LetterDetailFragmentVM?) {
        super.resumeFragment(viewModel)
        // 获取信件的id
        val letterId = publicViewModel!!.message.value!!.messageId
        viewModel!!.getLetterById(publicViewModel!!, letterId, this)
    }
}